<template>
	<div class="container">
		<div>
			<a-form ref="searchRef" :label-col="{style: { width: '100px' }}" :model="searchState" @finish="current=1;loading=true;initData()">
				<a-row :gutter="20">
					<a-col :span="6">
						<a-form-item label="选择项目">
							<a-select v-model:value="searchState.project_id" :show-search="true" placeholder="请选择项目" :options="projectOptions" option-filter-prop="label" allow-clear></a-select>
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="物料名称">
							<a-input v-model:value="searchState.material_name" placeholder="请输入" allow-clear></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="品牌">
							<a-select v-model:value="searchState.brand_id" :show-search="true" placeholder="请选择品牌" :options="brandList" option-filter-prop="label" allow-clear></a-select>
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item>
							<a-space>
								<a-button type="primary" html-type="submit">
									<search-outlined />搜索
								</a-button>
								<a-button v-permission="84" type="primary" @click="addPrice">
									<plus-outlined />添加价格记录
								</a-button>
							</a-space>
						</a-form-item>
					</a-col>
				</a-row>
			</a-form>
		</div>
		<div>
			<a-table v-if="!loading" :columns="columns" :scroll="tableScroll" row-key="id" children-column-name="children" :default-expand-all-rows="false" :data-source="source" :pagination="pagination" :loading="loading" @change="initData">
				<template #bodyCell="{ column, record }">
					<template v-if="column.dataIndex === 'price'">
						<template v-if="record.price">
							{{ record.price }}
						</template>
						<template v-else>
							<span style="color: red;">暂无</span>
						</template>
					</template>
					<template v-else-if="column.key === 'operation'">
						<a-space>
							<a-button v-permission="85" type="link" @click="editPrice(record)">
								<edit-outlined />设置价格
							</a-button>
							<a-button v-if="record.id" v-permission="86" type="link" @click="showPrice(record)">
								<snippets-outlined />查看历史价
							</a-button>
						</a-space>
					</template>
				</template>
			</a-table>
		</div>
		<a-modal v-model:visible="modalRef.visible" :width="400" :title="`设置价格`" @ok="setPrice">
			<a-form ref="formModalRef" :model="modalRef.form" v-bind="{labelCol: { style: { width: '80px' } }}">
				<a-form-item label="项目" name="project_id" :rules="{ required: true, message: '请选择项目' }">
					<a-select v-model:value="modalRef.form.project_id" :show-search="true" placeholder="请选择项目" :options="projectOptions" option-filter-prop="label" allow-clear :disabled="!!modalRef.form.id"></a-select>
				</a-form-item>
				<a-form-item label="物料名称" name="material_name" :rules="{ required: true, message: '请选择物料名称' }">
					<a-select v-model:value="modalRef.form.material_name" :show-search="true" placeholder="请选择项目" :options="modalMaterialOptions" option-filter-prop="label" allow-clear :disabled="!!modalRef.form.id"></a-select>
				</a-form-item>
				<a-form-item label="物料规格" name="model_name" :rules="{ required: true, message: '请选择物料规格' }">
					<a-select v-model:value="modalRef.form.model_name" :show-search="true" placeholder="请选择物料规格" :options="modalMaterialModelOptions" option-filter-prop="label" allow-clear :disabled="!!modalRef.form.id"></a-select>
				</a-form-item>
				<a-form-item label="计量单位" name="material_id" :rules="{ required: true, message: '请选择计量单位' }">
					<a-select v-model:value="modalRef.form.material_id" :show-search="true" placeholder="请选择计量单位" :options="modalMaterialUnitOptions" option-filter-prop="label" allow-clear :disabled="!!modalRef.form.id"></a-select>
				</a-form-item>
				<a-form-item label="品牌" name="brand_id" :rules="{ required: true, message: '请选择品牌' }">
					<a-select v-model:value="modalRef.form.brand_id" :show-search="true" placeholder="请选择品牌" :options="brandList" option-filter-prop="label" allow-clear :disabled="!!modalRef.form.id"></a-select>
				</a-form-item>
				<a-form-item label="设置日期" name="setting_date" :rules="{ required: true, message: '请输入设置日期' }">
					<a-date-picker v-model:value="modalRef.form.setting_date" :disabled-date="(date) => date && date > dayjs().endOf('day')" />
				</a-form-item>
				<a-form-item v-if="modalRef.form.setting_date && modalRef.form.brand_id && modalRef.form.material_id && modalRef.form.project_id" label="历史价格">
					{{ modalRef.form.history_price || '无' }}
				</a-form-item>
				<a-form-item label="价格" name="price" :rules="{ required: true, message: '请输入价格' }">
					<a-input-number v-model:value="modalRef.form.price" style="width: 100%;" placeholder="请输入价格" min="0" :precision="2" allow-clear></a-input-number>
				</a-form-item>
			</a-form>
		</a-modal>
	</div>
</template>
<script setup>
import { computed, getCurrentInstance, reactive, ref, watch } from "vue";
import { usePagination } from "vue-request";
import { post } from "@/utils/index.js";
import { EditOutlined, PlusOutlined, SearchOutlined, SnippetsOutlined } from "@ant-design/icons-vue";
import dayjs from "dayjs";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();
const searchRef = ref();
const formModalRef = ref();
const searchState = reactive({});
const brandList = ref([]);
const projectOptions = ref([]);
const query = route.query;
const modalRef = ref({
	visible: false,
	form: {},
	materialOptions: [],
});
post("dictionary", { root_id: 1414 }).then(data => {
	brandList.value = data;
});
post("price/fz/projects").then((data) => {
	projectOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
const columns = [
	{
		title: "序号",
		dataIndex: "id",
		key: "id",
		width: 80,
		align: "left",
		customRender: ({ text, record, index, column }) => {
			return index + 1;
		}
	},
	{
		title: "项目名称",
		dataIndex: "priceMaterial",
		sorter: false,
		width: 150,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text?.priceMaterialProjects?.[0].project?.name;
		}
	},
	{
		title: "物资名称",
		dataIndex: "priceMaterial",
		sorter: false,
		width: 150,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text?.material?.name;
		}
	},
	{
		title: "规格型号",
		dataIndex: "priceMaterial",
		sorter: false,
		width: 150,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text?.material?.model;
		}
	},
	{
		title: "计量单位",
		dataIndex: "priceMaterial",
		sorter: false,
		width: 100,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text?.material?.unit;
		}
	},
	{
		title: "品牌",
		dataIndex: "priceMaterial",
		sorter: false,
		width: 150,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text?.brand?.name;
		}
	},
	{
		title: "当前价格",
		dataIndex: "price",
		sorter: false,
		width: 100,
		ellipsis: true,
	},
	{
		title: "维护日期",
		dataIndex: "setting_date",
		sorter: false,
		width: 150,
		ellipsis: true,
	},
	{
		title: "维护人",
		dataIndex: "user",
		sorter: false,
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return text?.fullname;
		}
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 300,
		align: "center"
	}
];

const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 650 }));
const { data, loading, run, current, pageSize, total } = usePagination(params => post("price/fz", { ...params, ...searchState, material_type: 6 }), {
	defaultParams: [
		{
			page_size: 10
		}
	],
	pagination: {
		currentKey: "page",
		pageSizeKey: "page_size",
		totalKey: "total"
	}
});
const initData = (pag, filters, sorter) => {
	pag = Object.assign(
		{
			current: current.value,
			pageSize: pageSize.value
		},
		pag || {}
	);
	filters = { ...filters, ...searchState };
	const query = {};
	if (pag?.pageSize) {
		query['page_size'] = pag?.pageSize;
	}
	if (pag?.current) {
		query['page'] = pag?.current;
	}
	router.replace({ query: {
		...query,
		...filters
	}})
	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};
if (query) {
	if (query.project_id) searchState.project_id = parseInt(query.project_id);
	if (query.brand_id) searchState.brand_id = parseInt(query.brand_id);
	if (query.material_name) searchState.material_name = query.material_name;
	const pag = {};
	if (query.page) {
		pag['current'] = parseInt(query.page);
	}
	if (query.pageSize) {
		pag['pageSize'] = parseInt(query.page_size);
	}
	initData(pag);
}
const source = computed(() =>
	(data.value?.data || []).map(d => {
		if (d.children?.length === 0) delete d.children;
		return d;
	})
);
const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value
}));

const addPrice = () => {
	modalRef.value.visible = true;
	modalRef.value.form = {};
	post("price/fz/materials").then((data) => {
		modalRef.value.materialOptions = data;
	});
};
const modalMaterialOptions = computed(() => {
	const map = {};
	if (modalRef.value.form?.project_id) {
		for (const material of modalRef.value.materialOptions) {
			if (!(material.project_ids.includes(modalRef.value.form.project_id))) continue;
			if (map[material.name]) continue;
			map[material.name] = {
				value: material.name,
				label: material.name,
			};
		}
	}
	return Object.values(map);
})

const modalMaterialModelOptions = computed(() => {
	const map = {};
	if (modalRef.value.form?.material_name) {
		for (const material of modalRef.value.materialOptions) {
			if (material.name !== modalRef.value.form.material_name) continue;
			if (map[material.model]) continue;
			map[material.model] = {
				value: material.model,
				label: material.model,
			};
		}
	}
	return Object.values(map);
})

const modalMaterialUnitOptions = computed(() => {
	const map = {};
	if (modalRef.value.form?.model_name) {
		for (const material of modalRef.value.materialOptions) {
			if (material.model !== modalRef.value.form.model_name) continue;
			if (map[material.unit]) continue;
			map[material.unit] = {
				value: material.id,
				label: material.unit,
			};
		}
	}
	return Object.values(map);
})
const changeHistoryPrice = async () => {
	const form = modalRef.value.form;
	if (!form.project_id || !form.material_id || !form.brand_id || !form.setting_date) return;
	post("price/before/price", {
		id: form.id,
		project_id: form.project_id,
		material_id: form.material_id,
		brand_id: form.brand_id,
		setting_date: dayjs(form.setting_date.$d).format('YYYY-MM-DD')
	}).then(data => {
		modalRef.value.form.history_price = data.price;
	});
}

watch(() => modalRef.value.form.project_id, changeHistoryPrice);
watch(() => modalRef.value.form.material_id, changeHistoryPrice);
watch(() => modalRef.value.form.brand_id, changeHistoryPrice);
watch(() => modalRef.value.form.setting_date, changeHistoryPrice);

const setPrice = () => {
	formModalRef.value.validate().then(res => {
		proxy.$message.destroy();
		const params = { ...modalRef.value.form };
		params.setting_date = dayjs(params.setting_date.$d).format('YYYY-MM-DD')
		post("price/fz/save", params)
			.then(() => {
				proxy.$message.success("提交成功", 1);
				modalRef.value.visible = false;
				initData();
			})
			.catch(err => {
				proxy.$message.error(err);
			});
	})
		.catch(err => {});
}

const editPrice = record => {
	addPrice();
	modalRef.value.form = {
		id: record.id,
		project_id: record.priceMaterial?.priceMaterialProjects?.[0]?.project.id,
		price: record.price,
		material_name: record.priceMaterial?.material.name,
		model_name: record.priceMaterial?.material.model,
		material_id: record.priceMaterial?.material_id,
		brand_id: record.priceMaterial?.brand_id,
		setting_date: dayjs(record.setting_date)
	}
};
const showPrice = record => {
	router.push(`pricefz/history?material_id=${record.priceMaterial?.material_id}&project_id=${record.priceMaterial?.priceMaterialProjects[0]?.project.id}&brand_id=${record.priceMaterial?.brand_id}&material_type=${record.priceMaterial?.material_type}`);
}
</script>
<style scoped lang="scss">
.container {
  background: #fff;
  padding: 12px;
}
</style>